package com.waiter.agent;

import java.text.DecimalFormat;
import java.util.Calendar;

import manager.AppManager;
import models.DTO_MonAn;
import utils.MultiScreenHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class OrderBillActivity extends Activity {
	/** Called when the activity is first created. */
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;
	private int mAm_Pm;
	private String _am_pm = "";
	private Button _date;
	private Button _time;
	private AlertDialog alert;

	static final int TIME_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.orderbill);

		Button btnAddFood = (Button) findViewById(R.id.btnAddFood);
		btnAddFood.setOnClickListener(ButtonListener());

		Button btnCancel = (Button) findViewById(R.id.Cancel);
		btnCancel.setOnClickListener(ButtonListener());

		Button btnMore = (Button) findViewById(R.id.btnOptions);
		btnMore.setOnClickListener(ButtonListener());

		createMoreActionDialog();

		ScrollView foodList = (ScrollView) findViewById(R.id.food_list);
		foodList.setPadding(
				MultiScreenHelper.getInstance(this).getScrWidth() / 20, 0,
				MultiScreenHelper.getInstance(this).getScrWidth() / 25, 0);

		// LinearLayout foods = (LinearLayout) findViewById(R.id.foods);
		// for (int i = 0; i < 10; i++)
		// foods.addView(createItems("/burger.png", "Hambugger", 5000));

		_date = (Button) findViewById(R.id.EditDate);
		_time = (Button) findViewById(R.id.EditTime);
		_date.setOnClickListener(ButtonListener());
		_time.setOnClickListener(ButtonListener());

		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
		mAm_Pm = c.get(Calendar.AM_PM);
		updateDisplay();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		TextView total = (TextView) findViewById(R.id.VND);
		LinearLayout foods = (LinearLayout) findViewById(R.id.foods);

		// Remove notification to prevent duplication
		if (foods.findViewById(9909) != null)
			foods.removeView(foods.findViewById(9909));

		if (AppManager.getInstance().getFoodList() != null
				&& (AppManager.getInstance().getFoodList().isEmpty() == false)) {
			// Add food to list
			DTO_MonAn food;
			int totalAmount = 0;
			for (int i = 0; i < AppManager.getInstance().getFoodList().size(); i++) {
				food = AppManager.getInstance().getFoodList().get(i);
				foods.addView(createItems("/burger.png", food.getTenMon(),
						food.getGia()));
				totalAmount += food.getGia();
			}

			total.setText(totalAmount + " VND");
			AppManager.getInstance().clearFoodList();
		} else {
			// Create notification when list has no food
			LinearLayout addFood = new LinearLayout(getApplicationContext());
			addFood.setOrientation(LinearLayout.HORIZONTAL);
			addFood.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.WRAP_CONTENT));
			addFood.setGravity(Gravity.CENTER);
			addFood.setBackgroundResource(R.drawable.add_food_bg);
			addFood.setId(9909);

			ImageView icon = new ImageView(getApplicationContext());
			icon.setBackgroundResource(R.drawable.addfood2);
			icon.setScaleType(ScaleType.CENTER_INSIDE);
			icon.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT));
			addFood.addView(icon);

			TextView notification = new TextView(this);
			notification.setText(R.string.Notification);
			notification.setPadding(10, 20, 0, 20);
			notification.setTextSize(24);
			notification.setTextColor(Color.GRAY);
			notification.setGravity(Gravity.CENTER);
			notification.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT));
			addFood.addView(notification);

			addFood.setOnClickListener(ButtonListener());
			foods.addView(addFood);
			total.setText("0 VND");
		}
		super.onResume();
	}

	public View createItems(String imgPath, String name, int price) {

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(this.LAYOUT_INFLATER_SERVICE);
		View item = inflater.inflate(R.layout.ordered_item, null);

		ImageView foodImg = (ImageView) item.findViewById(R.id.food_img);
		foodImg.setPadding(
				MultiScreenHelper.getInstance(this).getScrWidth() / 40, 0,
				MultiScreenHelper.getInstance(this).getScrWidth() / 100, 0);
		foodImg.setImageResource(R.drawable.burger);

		TextView foodName = (TextView) item.findViewById(R.id.food_name);
		foodName.setText(name);

		TextView quantity = (TextView) item.findViewById(R.id.quantity);
		quantity.setPadding(
				MultiScreenHelper.getInstance(this).getScrWidth() / 60, 0, 0, 0);

		TextView foodPrice = (TextView) item.findViewById(R.id.price);
		foodPrice.setText(String.valueOf(price) + " VND");
		foodPrice
				.setPadding(
						MultiScreenHelper.getInstance(this).getScrWidth() / 50,
						0, 0, 0);

		LinedEditText note = (LinedEditText) item.findViewById(R.id.food_note);
		note.setTextSize(12);

		Button plus = (Button) item.findViewById(R.id.plus);
		Button minus = (Button) item.findViewById(R.id.minus);
		plus.setOnClickListener(ButtonListener());
		minus.setOnClickListener(ButtonListener());

		registerForContextMenu(item);
		return item;
	}

	public OnClickListener ButtonListener() {
		return new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.plus: {
					LinearLayout row = (LinearLayout) v.getParent();
					EditText t = (EditText) row.findViewById(R.id.quantity);
					int _value;
					if (t.getText().toString().compareTo("") == 0)
						_value = 0;
					else
						_value = Integer.parseInt(t.getText().toString());

					_value++;
					DecimalFormat df = new DecimalFormat("#00");
					t.setText(df.format(_value));
					break;
				}

				case R.id.minus: {
					LinearLayout row = (LinearLayout) v.getParent();
					EditText t = (EditText) row.findViewById(R.id.quantity);
					int _value;
					if (t.getText().toString().compareTo("") == 0)
						_value = 0;
					else
						_value = Integer.parseInt(t.getText().toString());

					if (_value > 0)
						_value--;
					DecimalFormat df = new DecimalFormat("#00");
					t.setText(df.format(_value));
					break;
				}

				case R.id.EditDate:
					showDialog(DATE_DIALOG_ID);
					break;

				case R.id.EditTime:
					showDialog(TIME_DIALOG_ID);
					break;

				case R.id.btnAddFood: {
					AppManager.getInstance().setState(
							AppManager.ADD_FOOD_EXISTING_BILL);
					Intent intent = new Intent(getApplicationContext(),
							ChooseFoodActivity.class);
					startActivity(intent);
					break;
				}

				case R.id.Cancel: {
					OrderBillActivity.this.finish();
					break;
				}
				case R.id.btnOptions: {
					alert.show();
					break;
				}
				case 9909: {
					AppManager.getInstance().setState(
							AppManager.ADD_FOOD_EXISTING_BILL);
					Intent intent = new Intent(getApplicationContext(),
							ChooseFoodActivity.class);
					startActivity(intent);
					break;
				}
				}

			}
		};
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);

		TextView title = (TextView) v.findViewById(R.id.food_name);
		menu.setHeaderTitle(title.getText());
		menu.add(0, v.getId(), 0, "Delete");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		LinearLayout foods = (LinearLayout) findViewById(R.id.foods);
		foods.removeViewAt(0);

		return super.onContextItemSelected(item);
	}

	/**
	 * Create a dialog for More Action button
	 */
	private void createMoreActionDialog() {
		final CharSequence[] actions = { "Delete multiple items",
				"View order history", "Help" };
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setTitle("More actions");
		alt_bld.setItems(actions, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				if (item == 1) {
					Intent intent = new Intent(getApplicationContext(),
							BillHistoryActivity.class);
					startActivity(intent);
				}
			}
		});

		alert = alt_bld.create();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
					false);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case TIME_DIALOG_ID:
			((TimePickerDialog) dialog).updateTime(mHour, mMinute);
			break;
		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			break;
		}
	}

	private void updateDisplay() {
		_date.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(mDay).append("/").append(mMonth + 1).append("/")
				.append(mYear).append(""));

		_time.setText(new StringBuilder().append(pad(mHour)).append(":")
				.append(pad(mMinute)).append(" ").append(_am_pm));

	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateDisplay();
		}
	};

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	/**
	 * A custom EditText that draws lines between each line of text that is
	 * displayed.
	 */
	public static class LinedEditText extends EditText {
		private Rect mRect;
		private Paint mPaint;

		// we need this constructor for LayoutInflater
		public LinedEditText(Context context, AttributeSet attrs) {
			super(context, attrs);

			mRect = new Rect();
			mPaint = new Paint();
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setColor(0x800000FF);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			int count = getLineCount();
			Rect r = mRect;
			Paint paint = mPaint;

			for (int i = 0; i < count; i++) {
				int baseline = getLineBounds(i, r);

				canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1,
						paint);
			}

			super.onDraw(canvas);
		}
	}

}
